/**
 * @file     addTwoNumbers.js
 * @brief    [2. 两数相加](https://leetcode-cn.com/problems/add-two-numbers/)
 * @author   Zhu
 * @date     2022-03-16 22:41
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    let head = null;
    let tail = null;

    let node1 = l1;
    let node2 = l2;
    let carry = 0;
    while (node1 !== null || node2 !== null) {
        const val1 = node1?.val ?? 0;
        const val2 = node2?.val ?? 0;

        const sum = val1 + val2 + carry;
        const value = sum % 10;
        carry = sum > 9 ? 1 : 0;

        if (head == null) {
            head = tail = new ListNode(value); // 初始化链表
        } else {
            tail.next = new ListNode(value);
            tail = tail.next;
        }

        node1 = node1?.next ?? null;
        node2 = node2?.next ?? null;
    }

    if (carry) tail.next = new ListNode(carry);

    return head;
};
